var utils = require('../util/common-util')

/**
 * Entity代码生成器
 */
var generator = {
    generate: function (json) {
        var tableName = json.tableName
        var tableFields = json.tableFields

        // 循环组装属性字段
        var fieldsOutput = ''
        tableFields.forEach(e => {
            var template
            if (e.tableId) {
                template =
                    '@TableId(value = "{1}", type = IdType.ASSIGN_ID)\r\n' +
                    '@ApiModelProperty(value = "{2}")\r\n' +
                    'private {4} {3};'

            } else {
                template =
                    '@TableField("{1}")\r\n' +
                    '@ApiModelProperty(value = "{2}")\r\n' +
                    'private {4} {3};'
            }
            template = template.replace('{1}', e.field.toUpperCase())
            template = template.replace('{2}', e.desc)
            template = template.replace('{3}', utils.convert2JavaName(e.field))
            template = template.replace('{4}', utils.convert2JavaType(e.type))
            fieldsOutput += template + "\r\n\r\n"
        });

        // 组装整个类模板
        var template =
            '@Data\r\n' +
            '@ApiModel(value = "{1}", description = "{2}")\r\n' +
            '@EqualsAndHashCode(callSuper = false)\r\n' +
            '@Accessors(chain = true)\r\n' +
            '@TableName("{3}")\r\n' +
            'public class {4} extends AbstractAuditableEntity {\r\n\r\n' +
            '{5}' +
            '}'
        template = template.replace('{1}', json.tableDesc)
        template = template.replace('{2}', json.tableDesc)
        var arr = tableName.split('_')
        var className = ''
        arr.forEach(o => {
            className += o[0].toUpperCase() + o.substring(1)
        })
        template = template.replace('{3}', tableName.toUpperCase())
        template = template.replace('{4}', className + 'Entity')
        template = template.replace('{5}', fieldsOutput)
        return template
    }
}

module.exports = generator